package com.atguigu.gulimall.product.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.TypeReference;
import com.atguigu.gulimall.product.service.CategoryBrandRelationService;
import com.atguigu.gulimall.product.viewVo.Catalog2Vo;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.google.common.collect.Lists;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.redisson.api.RLock;
import org.redisson.api.RedissonClient;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.cache.annotation.CachePut;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.cache.annotation.Caching;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.data.redis.core.ValueOperations;
import org.springframework.data.redis.core.script.DefaultRedisScript;
import org.springframework.stereotype.Service;

import java.util.*;
import java.util.concurrent.TimeUnit;
import java.util.stream.Collectors;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.atguigu.common.utils.PageUtils;
import com.atguigu.common.utils.Query;

import com.atguigu.gulimall.product.dao.CategoryDao;
import com.atguigu.gulimall.product.entity.CategoryEntity;
import com.atguigu.gulimall.product.service.CategoryService;
import org.springframework.transaction.annotation.Transactional;


@Service("categoryService")
@Slf4j
public class CategoryServiceImpl extends ServiceImpl<CategoryDao, CategoryEntity> implements CategoryService {


    @Autowired
    private CategoryBrandRelationService categoryBrandRelationService;

    @Autowired
    StringRedisTemplate redisTemplate;

    @Autowired
    RedissonClient redisson;

    @Override
    public PageUtils queryPage(Map<String, Object> params) {
        IPage<CategoryEntity> page = this.page(
                new Query<CategoryEntity>().getPage(params),
                new QueryWrapper<CategoryEntity>()
        );

        return new PageUtils(page);
    }

    @Override
    public List<CategoryEntity> listWithTree() {

        List<CategoryEntity> categoryEntities = baseMapper.selectList(null);

        return categoryEntities.stream().filter(m -> m.getParentCid() == 0).map(n -> {
            n.setChildren(getChildrens(n, categoryEntities));
            return n;
        }).sorted((a, b) -> {
            return (a.getSort() == null ? 0 : a.getSort()) - (b.getSort() == null ? 0 : b.getSort());
        }).collect(Collectors.toList());
    }

    @Override
    public void removeMenuByIds(List<Long> catIds) {

        //TODO
        baseMapper.deleteBatchIds(catIds);
    }

    @Override
    public Long[] findCatelogPath(Long catelogId) {
       List<Long> paths = Lists.newArrayList();
        findParentPath(catelogId, paths);
        Collections.reverse(paths);
        return paths.toArray(new Long[paths.size()]);
    }

    @Override
    public void update(CategoryEntity category) {
        this.updateById(category);
        //categoryBrandRelationService.updateCategory(category.getCatId(),category.getName());
    }

    @Override
    @Transactional
    //开启缓存删除功能，数据更新就将缓存清除, spel表达式， 常量
    /*@CacheEvict(value = "category", key = "'getLevelOneCategorys'") */
    //同时清除多个操作
    /*@Caching(evict = {
        @CacheEvict(value = "category", key = "'getLevelOneCategorys'")
    })*/
    //删除分区所有的数据, 双写模式, 查完数据给我放一份
    @CacheEvict(value = "category", allEntries = true)
    //@CachePut
    public void updateCascade(CategoryEntity category) {
        this.updateById(category);
        categoryBrandRelationService.updateCategory(category.getCatId(), category.getName());
    }

    //缓存穿透 ： 高并发查询不存在的数据， 缓存null处理
    //缓存雪崩 ： 大量的缓存key过期，高并发查询数据库， 设置随机过期时间
    //缓存击穿 ： 高并发查询一个过期的数据，导致数据库挂了   加锁， redission  获取setifab。。。。解决
    //表明将数据放入缓存，并设置分区，有缓存不掉方法  sync:: 加了同步锁，防止数据过期并发量过大导致频繁查询数据库
    @Cacheable(value = {"category"}, key = "#root.method.name", sync = true)
    public List<CategoryEntity> getLevelOneCategorys() {
        return baseMapper.selectList(Wrappers.<CategoryEntity>lambdaQuery().eq(CategoryEntity::getParentCid, 0));
    }

    //todo  堆外异常
    public Map<String, List<Catalog2Vo>> getCatelogJson() throws InterruptedException {

        ValueOperations<String, String> operations = redisTemplate.opsForValue();
        String catelogJSON = operations.get("catelogJSON");

        return StringUtils.isBlank(catelogJSON) ?
                getCatelogFromDbWithRedisLock(operations) : JSON.parseObject(catelogJSON, new TypeReference<Map<String, List<Catalog2Vo>>>(){});
    }

    //分布式锁解决方案(Redission)
    public Map<String, List<Catalog2Vo>> getCatelogFromDbWithRedissionLock(ValueOperations<String, String> operations) throws InterruptedException {

        RLock lock = redisson.getLock("catalogJson-lock");
        //如果获取到锁，加锁操作，业务执行期间自动续期，还有一种方法设置有效期，但不会自动续期，需要把过期时间调长
        lock.lock();

        Map<String, List<Catalog2Vo>> catelogFromDb = null;
        try{
            catelogFromDb = getCatelogFromDb(operations);
        }finally {
            lock.unlock();
        }

        return catelogFromDb;
    }

    //分布式锁解决方案(原生方案)
    public Map<String, List<Catalog2Vo>> getCatelogFromDbWithRedisLock(ValueOperations<String, String> operations) throws InterruptedException {

        //首先给redis lock加个标识
        String lockKey = UUID.randomUUID().toString();
        //然后设置redis锁
        if(operations.setIfAbsent("lock", lockKey, 300, TimeUnit.SECONDS)) {

            System.out.println("获取分布式锁成功！！！！！！！！！！！！！！");
            //成功，说明抢占锁成功， 这里try-finally，防止业务异常导致删锁操作不成功！
            Map<String, List<Catalog2Vo>> catelogFromDb = null;
            try{
                catelogFromDb = getCatelogFromDb(operations);
            }finally {
                //删锁操作， 这里删自己的锁，防止误删其他端口服务的锁导致业务出现异常，所有线程一股脑进来抢占锁！
                String luaDelLockkey = "if redis.call('get',KEYS[1]) == ARGV[1]\n" +
                        "then\n" +
                        "    return redis.call('del',KEYS[1])\n" +
                        "else\n" +
                        "    return 0\n" +
                        "end";

                Long lock = redisTemplate.execute(new DefaultRedisScript<Long>(luaDelLockkey, Long.class), Arrays.asList("lock"), lockKey);
            }
            return catelogFromDb;
        }else {
            //等待一下在执行！！！
            System.out.println("获取分布式锁失败，等待重试！！！！！！！！！！！！！！");
            Thread.sleep(200);
            return getCatelogFromDbWithRedisLock(operations);
        }
    }

    //测试缓存注解功能
    @Cacheable(value = "category", key = "#root.methodName")
    public Map<String, List<Catalog2Vo>> getCatelogFromDbCache(ValueOperations<String, String> operations) {


        // 一次性获取所有 数据
        List<CategoryEntity> selectList = baseMapper.selectList(null);
        //System.out.println("调用了 getCatalogJson  查询了数据库........【三级分类】");
        // 1）、所有1级分类
        List<CategoryEntity> level1Categorys = getParent_cid(selectList, 0L);

        // 2）、封装数据
        Map<String, List<Catalog2Vo>> collect = level1Categorys.stream().collect(Collectors.toMap(k -> k.getCatId().toString(), level1 -> {
            // 查到当前1级分类的2级分类
            List<CategoryEntity> category2level = getParent_cid(selectList, level1.getCatId());
            List<Catalog2Vo> catalog2Vos = null;
            if (category2level != null) {
                catalog2Vos = category2level.stream().map(level12 -> {
                    // 查询当前2级分类的3级分类
                    List<CategoryEntity> category3level = getParent_cid(selectList, level12.getCatId());
                    List<Catalog2Vo.Catalog3Vo> catalog3Vos = null;
                    if (category3level != null) {
                        catalog3Vos = category3level.stream().map(level13 -> {
                            return new Catalog2Vo.Catalog3Vo(level12.getCatId().toString(), level13.getCatId().toString(), level13.getName());
                        }).collect(Collectors.toList());
                    }
                    return new Catalog2Vo(level1.getCatId().toString(), catalog3Vos, level12.getCatId().toString(), level12.getName());
                }).collect(Collectors.toList());
            }
            return catalog2Vos;
        }));

        return collect;
    }

    public Map<String, List<Catalog2Vo>> getCatelogFromDb(ValueOperations<String, String> operations) {


        //单节点加锁  方案一
        //单节点所有请求进入该方法， 首先判断缓存
        //synchronized (this) {

        if(StringUtils.isNoneBlank(operations.get("catelogJSON"))) {
            String catelogJSON = operations.get("catelogJSON");
            return JSON.parseObject(catelogJSON, new TypeReference<Map<String, List<Catalog2Vo>>>(){});
        }

        System.out.println("查询了数据库！！！！！！！！！！！！！！！！");
        // 一次性获取所有 数据
        List<CategoryEntity> selectList = baseMapper.selectList(null);
        //System.out.println("调用了 getCatalogJson  查询了数据库........【三级分类】");
        // 1）、所有1级分类
        List<CategoryEntity> level1Categorys = getParent_cid(selectList, 0L);

        // 2）、封装数据
        Map<String, List<Catalog2Vo>> collect = level1Categorys.stream().collect(Collectors.toMap(k -> k.getCatId().toString(), level1 -> {
            // 查到当前1级分类的2级分类
            List<CategoryEntity> category2level = getParent_cid(selectList, level1.getCatId());
            List<Catalog2Vo> catalog2Vos = null;
            if (category2level != null) {
                catalog2Vos = category2level.stream().map(level12 -> {
                    // 查询当前2级分类的3级分类
                    List<CategoryEntity> category3level = getParent_cid(selectList, level12.getCatId());
                    List<Catalog2Vo.Catalog3Vo> catalog3Vos = null;
                    if (category3level != null) {
                        catalog3Vos = category3level.stream().map(level13 -> {
                            return new Catalog2Vo.Catalog3Vo(level12.getCatId().toString(), level13.getCatId().toString(), level13.getName());
                        }).collect(Collectors.toList());
                    }
                    return new Catalog2Vo(level1.getCatId().toString(), catalog3Vos, level12.getCatId().toString(), level12.getName());
                }).collect(Collectors.toList());
            }
            return catalog2Vos;
        }));

        //你能走到这里说明缓存没数据，加缓存
        operations.set("catelogJSON", JSON.toJSONString(collect), 1, TimeUnit.DAYS);
        return collect;
        //}
    }

    private void findParentPath(Long catelogId, List<Long> paths) {

        paths.add(catelogId);
        CategoryEntity byId = this.getById(catelogId);
        if(byId.getParentCid() != 0) {
            findParentPath(byId.getParentCid(), paths);
        };
    }
    public List<CategoryEntity> getChildrens(CategoryEntity root, List<CategoryEntity> all) {

        return all.stream().filter(m -> m.getParentCid() == root.getCatId()).map(n -> {
            n.setChildren(getChildrens(n, all));
            return n;
        }).sorted((a, b) -> {
            return (a.getSort() == null ? 0 : a.getSort()) - (b.getSort() == null ? 0 : b.getSort());
        }).collect(Collectors.toList());
    }

    private List<CategoryEntity> getParent_cid(List<CategoryEntity> selectList, Long parent_cid) {
        return selectList.stream().filter(item -> item.getParentCid() == parent_cid).collect(Collectors.toList());
    }

}